package com.lxz.aiagentbackend.app;

import com.lxz.aiagentbackend.advisor.MyLoggerAdvisor;
import com.lxz.aiagentbackend.advisor.ReReadingAdvisor;
import com.lxz.aiagentbackend.chatmomory.FileBasedChatMemory;
import com.lxz.aiagentbackend.rag.FitnessCoachAppVectorStoreConfig;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;
@Slf4j
@Component
public class FitnessCoachApp {

    @Resource
    private VectorStore fitnessCoachAppVectorStore;

    @Resource
    private ToolCallback[] allTools;

    private final ChatClient chatClient;

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    // 健身报告
    public record FitnessReport(String title, List<String> suggestions) {
    }


    private static final String SYSTEM_PROMPT = "我是一名深耕健身领域多年的专业教练。从现在起，无论你遇到什么健身难题，都能放心向我倾诉！\u200B\n" +
            "我想先了解下你的健身状态：如果你还是健身新手，对如何开启健身计划、拓展运动社交圈感到迷茫，或是不知道怎么制定适合自己的训练目标，可以和我说说；要是你已经处于进阶训练阶段，在突破训练瓶颈、解决运动损伤，又或是因健身习惯与身边人产生矛盾方面有困扰，欢迎详细聊聊；而对于健身爱好者们，在长期坚持健身与平衡家庭、工作责任，以及处理因健身理念不同引发的社交问题上，有任何难题都能告诉我。\u200B\n" +
            "请详细讲讲事情的经过，比如训练过程中的具体表现、身体的反应，还有你内心的想法和期待，这样我就能为你量身定制专属的健身解决方案和健身饮食的饮食计划";





    public FitnessCoachApp(ChatModel dashscopeChatModel) {
        // 1. 初始化基于内存的对话记忆
        ChatMemory chatMemory = new InMemoryChatMemory();
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),// 对话记忆拦截器
                        // 自定义推理增强 Advisor，可按需开启
                        new ReReadingAdvisor(),
                        new MyLoggerAdvisor()
                )
                .build();
    }

//    public FitnessCoachApp(ChatModel dashscopeChatModel) {
//        // 1. 初始化基于内存的对话记忆
//        String fileDir=System.getProperty("user.dir")+"/chat-memory";
//        FileBasedChatMemory fileBasedChatMemory = new FileBasedChatMemory(fileDir);
//        chatClient = ChatClient.builder(dashscopeChatModel)
//                .defaultSystem(SYSTEM_PROMPT)
//                .defaultAdvisors(
//                        new MessageChatMemoryAdvisor(fileBasedChatMemory),// 对话记忆拦截器
//                        // 自定义推理增强 Advisor，可按需开启
//                        new ReReadingAdvisor(),
//                        new MyLoggerAdvisor()
//                )
//                .build();
//    }

    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        System.out.println( content);
        return content;
    }

    /**
     * @description: 生成报告
     * @author: liuxinzhi
     * @date: 2025/9/5 11:21
     * @param: [message, chatId]
     * @return: com.lxz.aiagentbackend.app.FitnessCoachApp.FitnessReport
     **/

    public FitnessReport doChatWithReport(String message, String chatId) {
        FitnessReport fitnessReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成健身咨询报告，标题为{用户名}的健身咨询报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(FitnessReport.class);
        log.info("fitnessReport: {}", fitnessReport);
        return fitnessReport;
    }

    /**
     * @description: 使用Rag
     * @author: liuxinzhi
     * @date: 2025/9/5 11:21
     * @param: [message, chatId]
     * @return: java.lang.String
     **/

    public String doChatWithRag(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                // 应用知识库问答
                .advisors(new QuestionAnswerAdvisor(fitnessCoachAppVectorStore))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    /**
     * @description: 使用工具
     * @author: liuxinzhi
     * @date: 2025/9/5 11:21
     * @param: [message, chatId]
     * @return: java.lang.String
     **/
    public String doChatWithTools(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                // 应用知识库问答
                .advisors(new QuestionAnswerAdvisor(fitnessCoachAppVectorStore))
                .tools(allTools)
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


    public String doChatWithMcp(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    public Flux<String> doChatByStream(String message, String chatId) {
        return chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .stream()
                .content();
    }

}
